package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.base.model.Result;
import com.xuecheng.base.model.ResultUtil;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {

    @Autowired
    TeachplanMapper teachplanMapper;

    @Autowired
    TeachplanMediaMapper teachplanMediaMapper;
    /**
     * 获取课程计划
     * @author hjh
     * @date 2023/5/6 11:42
     * @param courseId
     * @return List<TeachplanDto>
     */

    @Override
    public List<TeachplanDto> getTreeNodes(Long courseId) {
        // 获取课程计划和媒资信息
        List<TeachplanDto> teachplanDtoList = teachplanMapper.selectTreeNodes(courseId);
        

        return teachplanDtoList;
    }

    /**
     * 保存课程章节
     * @author hjh
     * @date 2023/5/6 14:47
     * @param saveTeachplanDto

     */

    @Override
    public void saveTeachplan(SaveTeachplanDto saveTeachplanDto) {
        Long id = saveTeachplanDto.getId();
        if(id!=null){
            Teachplan teachplan = teachplanMapper.selectById(id);
            BeanUtils.copyProperties(saveTeachplanDto,teachplan);
            teachplanMapper.updateById(teachplan);
        }else {
            //取出同父同级别的课程计划数量
            int count = getTeachplanCount(saveTeachplanDto.getCourseId(), saveTeachplanDto.getParentid());
            Teachplan teachplanNew = new Teachplan();
            //设置排序号
            teachplanNew.setOrderby(count+1);
            BeanUtils.copyProperties(saveTeachplanDto,teachplanNew);
            teachplanMapper.insert(teachplanNew);
        }
    }

    /**
     * 通过课程计划id删除课程计划
     *
     * @param teachplanId
     * @return String
     * @author hjh
     * @date 2023/5/6 16:27
     */

    @Transactional
    @Override
    public Result deleteTeachplan(Long teachplanId) {
        List<Teachplan> teachplans = teachplanMapper.selectList(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getParentid, teachplanId));
        if (teachplans.size() != 0){
            return ResultUtil.error(120409,"课程计划信息还有子级信息，无法操作");
        }
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if(teachplan==null){
            XueChengPlusException.cast("课程计划不存在");
        }
        teachplanMapper.deleteById(teachplanId);
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,teachplan.getId()));

        // 将同级的所有orderby字段减一
        List<Teachplan> teachplans1 = teachplanMapper.selectList(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getParentid, teachplan.getParentid()));
        teachplans1.stream().filter(item->item.getId()!=teachplanId)
                .map(item->{
                    item.setOrderby(item.getOrderby()-1);
                    return item;
                }).forEach(item->teachplanMapper.updateById(item));
//        teachplans = teachplans.stream().filter(item -> item.getId() != teachplanId).collect(Collectors.toList());
//        System.out.println("+++++++++++++++++++++"+teachplans.toString());
//        teachplans = teachplans.stream().map(item -> {
//            item.setOrderby(item.getOrderby() - 1);
//            return item;
//        }).collect(Collectors.toList());
//        System.out.println("=================="+teachplans.toString());
//                .forEach(item -> teachplanMapper.updateById(item));

        return ResultUtil.success(null);
    }

    /**
     * 移动小节
     * @author hjh
     * @date 2023/5/6 21:57
     * @param movetype
     * @param id

     */

    @Override
    public void move(String movetype, Long id) {
        if(movetype.equals("movedown")){
            // 判断该小节下面是否有小节
            Teachplan teachplan = teachplanMapper.selectById(id);
            if(teachplan!=null && teachplan.getParentid() != 0L){
                List<Teachplan> teachplanList = teachplanMapper.selectList(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getParentid, teachplan.getParentid()).orderByAsc(Teachplan::getOrderby));
                int index = teachplanList.indexOf(teachplan);
                if(teachplanList.size() > index+1){
                    // 有则交换排序字段
                    int orderByTemp = teachplan.getOrderby();
                    teachplan.setOrderby(teachplanList.get(index + 1).getOrderby());
                    teachplanMapper.updateById(teachplan);
                    Teachplan teachplan1 = teachplanList.get(index + 1);
                    teachplan1.setOrderby(orderByTemp);
                    teachplanMapper.updateById(teachplan1);
                }else {
                    XueChengPlusException.cast("小节已经是最后一节，不能移动");
                }
            }


        }
        if(movetype.equals("moveup")){
            // 判断该小节上面是否有小节
            Teachplan teachplan = teachplanMapper.selectById(id);
            if(teachplan!=null && teachplan.getParentid() != 0L){
                List<Teachplan> teachplanList = teachplanMapper.selectList(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getParentid, teachplan.getParentid()).orderByAsc(Teachplan::getOrderby));
                int index = teachplanList.indexOf(teachplan);
                if(index>0){
                    // 有则交换排序字段
                    int orderByTemp = teachplan.getOrderby();
                    teachplan.setOrderby(teachplanList.get(index - 1).getOrderby());
                    teachplanMapper.updateById(teachplan);
                    teachplanList.get(index-1).setOrderby(orderByTemp);
                    teachplanMapper.updateById(teachplanList.get(index+1));
                }else{
                    XueChengPlusException.cast("小节已经是第一节，不能上移");
                }
            }
            // 有则交换排序字段
        }
        return;
    }

    @Override
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if(teachplan == null){
            XueChengPlusException.cast("课程计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if(grade!=2){
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }
        //课程id
        Long courseId = teachplan.getCourseId();

        //先删除原来该教学计划绑定的媒资
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,teachplanId));
        //再添加教学计划与媒资的绑定关系
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        teachplanMedia.setCourseId(courseId);
        teachplanMedia.setTeachplanId(teachplanId);
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setMediaId(bindTeachplanMediaDto.getMediaId());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMediaMapper.insert(teachplanMedia);
        return teachplanMedia;
    }

    @Override
    public Result deleteAssociationMedia(Long teachPlanId, String mediaId) {
        int delete = teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getId, teachPlanId).eq(TeachplanMedia::getMediaId, mediaId));
        if (delete <0){
            XueChengPlusException.cast("删除失败");
        }
        return ResultUtil.success("删除成功");
    }

    /**
     * @description 获取最新的排序号
     * @param courseId  课程id
     * @param parentId  父课程计划id
     * @return int 最新排序号
     * @author Mr.M
     * @date 2022/9/9 13:43
     */
    private int getTeachplanCount(long courseId,long parentId){
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,courseId);
        queryWrapper.eq(Teachplan::getParentid,parentId);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return count;
    }
}
